// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import BaseView from "../base/BaseView";
import KLineTrendComponent from "../base/components/KLineTrendComponent";
import { ThsRankData } from "./models/ThsRankData";

const {ccclass, property} = cc._decorator;

@ccclass
export default class PlateCompareView extends BaseView {

    @property(cc.Prefab)
    klineTrendPrefab: cc.Prefab = null;

    @property(cc.Node)
    contents: cc.Node[] = [];

    @property(cc.Label)
    labelNames: cc.Label[] = [];

    @property(cc.Label)
    startDate: cc.Label = null;
    
    @property(cc.Label)
    endDate: cc.Label = null;

    klineTrends: KLineTrendComponent[] = [];


    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        for (let index = 0; index < this.contents.length; index++) {
            const content = this.contents[index];
            let node = cc.instantiate(this.klineTrendPrefab);
            node.height = content.height;
            content.addChild(node);
            this.klineTrends[index] = node.getComponent(KLineTrendComponent);
        }
    }

    show(params?: Object): void {
        super.show(params);
        for (let index = 0; index < this.contents.length; index++) {
            let key = 'item' + (index + 1);
            let item = params[key];
            this.labelNames[index].string = item.name;
            this.refreshView(index, item.ts_code);
        }
    }

    onBtnName (event, param) {
        let index = parseInt(param);
        let params = {
            selects: [],
            callback: (plateNode) => {
                let ts_code = plateNode.ts_code;
                this.refreshView(index, ts_code);
            },
            isSingle: true,
        };
        this.createDialog(BaseView.Views.SelectPlateView, params);
    }

    refreshView (index: number, ts_code: string) {
        let rankData = ThsRankData.getInstance().getRankData(ts_code);
        this.labelNames[index].string = rankData.name;
        let content = this.contents[index];
        let list = rankData.list;
        this.startDate.string = list[0].date.slice(4,8);
        this.endDate.string = list[list.length - 1].date.slice(4,8);

        let nodeWidth = Math.floor((content.width - 50) / (list.length + 1));
        if (nodeWidth < 10) {
            nodeWidth = 10;
        } 

        if (nodeWidth > 40) {
            nodeWidth = 40;
        }

        this.startDate.node.x = nodeWidth;
        this.endDate.node.x = nodeWidth * list.length;
        this.klineTrends[index].setData(rankData, nodeWidth, 50);
    }

    // update (dt) {}
}
